package com.timous.service;


import com.timous.Entity.Blog;
import com.timous.Entity.Type;
import com.timous.NotFoundException;
import com.timous.dao.BlogRepository;
import com.timous.util.MarkdownUtils;
import com.timous.util.MyBeanUtils;
import com.timous.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import javax.swing.text.StyledEditorKit;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    //注入dao层的对象
    @Autowired
    private BlogRepository blogRepository;

    //获取博客
    @Override
    public Blog getBlog(Long id) {
        return blogRepository.getOne(id);
    }

    //前端转化
    @Override
    public Blog getAndConvert(Long id) {

        Blog blog = blogRepository.getOne(id);

        if(blog == null){

            throw new NotFoundException("博客不存在");

        }

        Blog b = new Blog();

        BeanUtils.copyProperties(blog , b);

        String content = b.getContent();

        String htmlContent = MarkdownUtils.markdownToHtmlExtensions(content);



        //会操作数据库
        b.setContent(htmlContent);

        blogRepository.updateViews(id);

        return b;

    }

    //实现分页的查询
    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blogQuery) {
        //Jpa已经帮忙封装好了对于复杂的查询，但是需要实现一个接口
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            /*处理动态查询的条件
            root代表你动态查询的对象，这里也就是blog，映射到了root
            CriteriaQuery是条件的容器，设置条件的具体的表达式*/
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!"".equals(blogQuery.getTitle()) && blogQuery.getTitle() != null) {
                    //通过标题模糊查询
                    predicates.add(cb.like(root.<String>get("title"), "%" + blogQuery.getTitle() + "%"));
                }
                //构造分类的查询条件
                if (blogQuery.getTypeId() != null) {
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blogQuery.getTypeId()));
                }
                //是否推荐来进行查询
                if (blogQuery.isRecommend()) {
                    predicates.add(cb.equal(root.<Boolean>get("recommend"), blogQuery.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);
    }

    //保存一片博客
    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
        if (blog.getId() == null) {
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            //浏览的次数
            blog.setViews(0);
        } else {
            blog.setUpdateTime(new Date());
        }
        //创建一个当前的时间，成为博客的发布的时间

        return blogRepository.save(blog);
    }

    //更新博客
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Blog b = blogRepository.getOne(id);
        if (b == null) {
            throw new NotFoundException("该博客不存在！");
        }

        //只把属性里面有东西的考到b里面，相当于只修改对应的有修改的地方
        //前面的时数据源，后面的是目标，把数据源考到目标里面
        BeanUtils.copyProperties(blog, b, MyBeanUtils.getNullPropertyNames(blog));
        //修改更新的时间
        b.setUpdateTime(new Date());
        return blogRepository.save(b);
    }

    //删除博客
    @Transactional
    @Override
    public void deleteBlog(Long id) {
        blogRepository.deleteById(id);
    }

    //前台的主页的展示
    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogRepository.findAll(pageable);
    }


    //根据tagid 查询对应的博客
    @Override
    public Page<Blog> listBlog(Long tagId, Pageable pageable) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                Join join = root.join("tags");

                return cb.equal(join.get("id"), tagId);
            }
        } , pageable);
    }

    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        Pageable pageable = PageRequest.of(0, size, sort);
        return blogRepository.findTop(pageable);
    }

    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {
        return blogRepository.findByQuery(query, pageable);
    }

    @Override
    public Map<String, List<Blog>> achiveBlog() {

        List<String> years = blogRepository.findGroupYear();

        Map<String, List<Blog>> map = new HashMap<>();

        for (String year:years) {
            map.put(year , blogRepository.findByYear(year));
        }

        return map;
    }

    @Override
    public Long countBlog() {
        return blogRepository.count();
    }

}
